﻿
using StructureMap;
using StructureMap.Pipeline;

namespace Foothill.IoC
{
    public abstract class IocModule
    {
        public abstract void RegisterTypes();

        public void Register<TInterface, TClass>() where TClass : TInterface
        {
            Register<TInterface, TClass>(InstanceLifetime.Transient);
        }

        public void Register<TInterface, TClass>(InstanceLifetime instanceLifetime) where TClass : TInterface
        {
            ILifecycle lifecycle = GetInstanceLifeCycle(instanceLifetime);
            ObjectFactory.Configure(x => x.For<TInterface>().LifecycleIs(lifecycle).Use<TClass>());
        }

        protected void Register<TInterface, TClass>(InstanceLifetime instanceLifetime, string instanceKey) where TClass : TInterface
        {
            ILifecycle lifecycle = GetInstanceLifeCycle(instanceLifetime);
            ObjectFactory.Configure(x => x.For<TInterface>().LifecycleIs(lifecycle).Use<TClass>().Named(instanceKey));
        }

        private static ILifecycle GetInstanceLifeCycle(InstanceLifetime instanceLifetime)
        {
            ILifecycle lifeCycle;
            if (instanceLifetime == InstanceLifetime.Singleton)
            {
                lifeCycle = new SingletonLifecycle();
            }
            else if (instanceLifetime == InstanceLifetime.HttpContext)
            {
                lifeCycle = new HttpContextLifecycle();
            }
            else
            {
                lifeCycle = new UniquePerRequestLifecycle();
            }

            return lifeCycle;
        }
    }
}
